# -*- coding: utf-8 -*-
import requests
import time
from   requests_html import HTMLSession
import json
import os
import sys
import glob
import datetime
import threadpool
import base64
import db
from html.parser import HTMLParser
from bs4 import BeautifulSoup
from functools import reduce 
import re
import csv

class Consultant:
    def __init__(self,cid,role,name,grade):
        self.cid = cid
        self.role = role
        self.name = name
        self.grade = grade

    def __str__(self):
        return "{} {} {}".format(self.name,self.role,self.grade)

class Assignment:
    def __init__(self,project,consultant,start,end,effort = 1,role = ""):
        self.project = project
        self.role = role
        self.consultant = consultant
        self.startsOn = start
        self.endsOn = end
        self.effort = effort

    def __str__(self):
        return "{} {}({}) {} {}".format(self.project,self.consultant,self.role,self.startsOn,self.endsOn)

class Project:
    def __init__(self,name,pid):
        self.pid = pid
        self.name = name
    def __str__(self):
        return "{},{}".format(self.pid,self.name)

class Jigsaw:
    def __init__(self,session):
        self.session = HTMLSession()
        self.session.headers.update({"Cookie":"_jigsaw_session={}".format(session)})
        self.projects = []
        self.assignments = []

    def getAccount(self,accountId):
        response = self.session.get(url = "https://jigsaw.thoughtworks.net/accounts/{}.json".format(accountId)).json()
        with open("../jigsaw/{}.json".format(accountId), 'w', encoding='utf8') as file:
            json.dump(response, file)

    def parseAccount(self,accountId):
        data = json.load(open("../jigsaw/{}.json".format(accountId),encoding='utf8'))
        for i in data["teams"]:
            self.parseAssignments(i["spots"])
    
    def parseProjects(self,accountId):
        data = json.load(open("../jigsaw/{}.json".format(accountId),encoding='utf8'))
        for i in data["teams"]:
            for j in i["spots"]:
                projectId = re.split("/|\?",j["projectUrl"])[-2]
                self.projects.append(Project(i["name"],projectId))
                break
        for i in self.projects:
            print(i)

    def parseAssignments(self,spots):
        for i in spots:
            project = re.split("/|\?",i["projectUrl"])[-2]
            for j in i["assignments"]:
                info = j["consultant"]
                self.assignments.append(Assignment(project,Consultant(info["id"],info["role"],info["name"],info["grade"]),j["startsOn"],j["endsOn"]))

    def getProject(self,projectId):
        with open("../jigsaw/{}.html".format(projectId), 'w', encoding='utf8') as file:
            data = self.session.get(url = "https://jigsaw.thoughtworks.net/projects/{}".format(projectId)).text
            file.write(data)

    def parse(self,projectId):
        people = []
        with open("../jigsaw/{}.html".format(projectId), 'r', encoding='utf8') as file:
            soup = BeautifulSoup(file.read(),"html")
            x = soup.find_all(id = 'current_assignments')
            rows = x[0].find(id = "proxy_list").find_all('tr')

            for i in rows:
                cells = i.find_all('td')
                role,name,grade,start,end = cells[0].string.strip(),cells[1].a.string,cells[2].string,cells[6].string,cells[7].string
                people.append(Consultant(role,name,grade))
        print(projectId)
        print(len(list(filter(lambda x: "Developer" in x.role,people))))

    def getCSV(self,accountId):
        response = self.session.get(url = "https://jigsaw.thoughtworks.net/accounts/export_all/{}".format(accountId),stream=True)
        with open("../jigsaw/{}.csv".format(accountId), 'wb') as file:
            file.write(response.content)

    def parseCSV(self,accountId):
# Employee ID,Assignee,Gender,Role,Assignment Start Date,
# End Date,Effort(%),Probability(%),Grade,Staffing Office,
# Working Office,Profile Working Office,Shadow,Project,Project Earliest Start Date,
# Project Duration(Months),Opportunity Owner,Rate Type,Account,Parent Account
        with open("../jigsaw/{}.csv".format(accountId), 'r', encoding='utf8') as file:
            csv_reader = csv.reader(file, delimiter=',')
            next(csv_reader)
            for row in csv_reader:
                # project,consultant,start,end,effort = 1,role = ""
                self.assignments.append(Assignment(row[13],row[1],datetime.datetime.strptime(row[4],"%b-%d-%Y"),datetime.datetime.strptime(row[5],"%b-%d-%Y"),row[6],row[3]))
        return self.assignments

    def getAssignmentOfDate(self,project,date):
        x = list(filter(lambda x:x.project == project and x.startsOn < date and x.endsOn > date ,self.assignments))
        for i in x:
            print(i)


# accounts = [{"jigsaw":"31798","name":"Daimler CN"},
# {"jigsaw":"31980","jira":"CMB"},
# {"jigsaw":"31975","jira":"Starbucks"},
# {"jigsaw":"30037","jira":"Huawei"}]
# for i in accounts:
	# Jigsaw("79495d23e74a52388dce768d5c30a847").getAccount(i["jigsaw"])
# Jigsaw("79495d23e74a52388dce768d5c30a847").getAssignmentOfDate(30037)
# Jigsaw("79495d23e74a52388dce768d5c30a847").getAssignmentOfDate(3179831798,datetime.datetime.now())
# Jigsaw("79495d23e74a52388dce768d5c30a847").getAccount(35903)
# Jigsaw("79495d23e74a52388dce768d5c30a847").parseProjects(35903)
# Jigsaw("79495d23e74a52388dce768d5c30a847").getCSV(35903)
j = Jigsaw("79495d23e74a52388dce768d5c30a847")
j.parseCSV(35903)
j.getAssignmentOfDate("Atlas Extension Project",datetime.datetime(2018,10,10))
# projects = [{"jigsaw":"45132","jira":"SMP"},
# {"jigsaw":"43792","jira":"SRM"},
# {"jigsaw":"41604","jira":"MBB"},
# {"jigsaw":"41808","jira":"OTR"},
# {"jigsaw":"41809","jira":"OTAS"},{"jigsaw":"45619","jira":"NAP3"}]
# for i in projects:
# 	Jigsaw("79495d23e74a52388dce768d5c30a847").parse(i["jigsaw"])


